import { PureComponent } from "react";
import { SearchBar,Carousel,Grid,Flex,TabBar,Button,PullToRefresh,ListView} from "antd-mobile"
import { ActivityIndicator } from 'antd-mobile';
import { connect } from 'dva';
import { Row, Col,Select } from 'antd';
import { handleImg, goToPage,isNull,handleOSS } from "../../utils/helper";
import {IntlProvider, addLocaleData,FormattedMessage} from 'react-intl';
import localeData from '../../../public/lang/data.json';
import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
import MToast from '../../components/Util/MToast';
import ReactDOM from 'react-dom';
import Macy from 'macy';
const Option = Select.Option;
@connect(() => {
  return ({

  })
})
export default class MelaShop extends PureComponent{
  constructor(props){
    super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2 // rowHasChanged(prevRowData, nextRowData); 用其进行数据变更的比较
    })
    this.state = {
      carouselItem:[],
      loading:true,
      dataSource,
     newsList:[],
     pages:{
        pageNum:1,
       pageSize:20
     },
      hasMore: true,
      refreshing: true,
      isLoading: true,
      selectedTab: 'redTab',
      onImg:true,
      locale:'it',
      isOption:false,
      height: document.documentElement.clientHeight,
      useBodyScroll: true,
      IsImage:false,
      masonry:false,
    }
  }
  componentDidUpdate() {
    if (this.state.useBodyScroll) {
      document.body.style.overflow = 'auto';
    } else {
      document.body.style.overflow = 'hidden';
    }

  }
  componentDidMount() {
    console.log(ReactDOM.findDOMNode(this.lv))
    // const hei = this.state.height - ReactDOM.findDOMNode(this.lv).offsetTop;
    console.log(this.state.height)

    // setTimeout(() => {
    //
    //   this.setState({
    //
    //     height: hei,
    //
    //   });
    // }, 1500);
  }
  componentWillMount(){
    let {dispatch,location} = this.props;

this.bannerList();
 this.goodContent(this.state.pages);

    if(localStorage.locale=='it'){
      this.setState({
        locale:'it',
        isOption:false
      })
    }else if(localStorage.locale=='zh'){
      this.setState({
        locale:'zh',
        isOption:true
      })
    }else{
      localStorage.setItem("locale",'it')
      this.setState({
        locale:'it',
        isOption:false
      })
    }

  }
  getMacy = () => {
    if (this.state.masonry) {
      this.state.masonry.reInit()
    } else {
      let masonry = new Macy({
        container: '.list-view-section-body', // 图像列表容器
        trueOrder: false,
        waitForImages: false,
        useOwnImageLoader: false,
        debug: true,
        margin: { x: 13, y: 4 },    // 设计列与列的间距
        columns: 2,    // 设置列数
      })
      this.setState({ masonry })
    }
  }
  bannerList(){
    let {dispatch,location} = this.props;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "qry/all?_c=app_banner_list",
          params: [
          ],
          _c: "app_banner_list"
        },
        callback: (result) => {
          let { data } = result;
          this.setState({
            carouselItem:data,
            loading:false,

          })
          console.log(data)

        }
      }
    });
  };
  goodContent(pages){
    let {dispatch,location} = this.props;
    let _this = this;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "lv/data?_c=app_goods_page_list",
          params: [
            {
              key: "page_index",
              value: 1
            },
            {
              key: "page_size",
              value: 20
            },
          ],
          _c: "app_goods_page_list"
        },
        callback: (result) => {
          let { data } = result;
          console.log(data.list);
          console.log(data.list[0].store_id)
          localStorage.setItem("store_id",data.list[0].store_id)
          const len = data.list.length;
          if(data.count/20>=this.state.pages.pageNum){
            this.state.pages.pageNum++;
            this.state.newsList=[...this.state.newsList,...data.list]
            this.setState({
              newsList:this.state.newsList,
              dataSource: this.state.dataSource.cloneWithRows(this.state.newsList),
              isLoading: false,
              pages:this.state.pages,
            })
          }else{
            console.log("ggg")
            this.setState({
              newsList:this.state.newsList,
              dataSource: this.state.dataSource.cloneWithRows(data.list),
              isLoading: false,
              pages:this.state.pages,
            })
          }
          this.setState({
            refreshing:false
          })
          this.getMacy()
        }
      }
    });
  }
  // 滑动到底部时加载更多
  onEndReached = (event) => {//触底加载
    if (this.state.isLoading) {
      return;
    }
    this.setState({ isLoading: true });
    setTimeout(() => {
      this.goodContent(this.state.pages)
    }, 600);
  }


  goodList() {
    let { dataSource} = this.state;

    if (!dataSource || dataSource.length == 0) {
      return (
        <div style={{ padding: "40px 0", textAlign: "center", fontSize: "20px", color: "#555" }}>
          {T(localeData[localStorage.locale].goodsDetailCartNoGood)}
        </div>
      )
    }
    else {
      let contents = [];
      return (
        <div className="box" style={{height:'100%',paddingBottom:'20%'}}>
          {dataSource.map((i,k) => (
            <div  key={k} style={{background:'#fff',fontWeight:'bold',padding:'5% 5% 5%',borderRadius:'10px'}} className="item">
              <div onClick={(e)=>{this.handleDetail(e,i)}}>
                <img src={handleOSS(i.img_url)} style={{width:'100%',height:'100%'}}/>
              </div>
              <div style={{overflow:'hidden',margin:'10% 0px 0px'}}>
                <p className="ellipsis2" style={{margin:'12px 0px 0px',textAlign:'left',color:'#595867',fontSize:'13px',}}>{i.goods_name}</p>
                <div style={{overflow:'hidden',marginTop:'8px'}}>
                  <div style={{float:'left',color:'#F09600',fontSize:'15px',marginTop:'5px'}}>€{i.price}</div>
                  <div style={{float:'right',width:'34px',height:'34px'}} onClick={(e) => {this.handleAdd(e,i) }}>
                    <img src="image/cart1.png" style={{width:'32px',height:'32px'}}/>
                  </div>
                </div>

              </div>

              {/*<Button type="primary" size="small" inline style={{marginBottom:'1em'}} onClick={(e) => {this.handleAdd(e,i) }}>+ADD</Button>*/}
            </div>

          ))}
        </div>

      )
    }
  }
  handleDetail=(e,i)=>{
    let {dispatch} = this.props;
    goToPage({ dispatch, config: { url: "/goodsDetail?id="+i.id+"&store_id="+i.store_id+"&status="+i.status }, isReplace: false })
  }
  handleAdd=(e,i)=>{
    console.log(i);

    let {dispatch} = this.props;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "cart/add",
          params: [
            {
              key: "goods_id",
              value: i.id
            },
            {
              key: "goods_name",
                value: i.goods_name
            },
            {
              key: "img_url",
                value: i.img_url
            },
            {
              key: "price",
                value: i.price
            },
            {
              key: "quantity",
                value: 1
            }

          ]
        },
        callback: (result) => {
          let { data } = result;
       console.log(data)
          if(data.status=="0"){
              alert("该商品已下架")
          }else{
            MToast.info(T(localeData[localStorage.locale].goodsDetailCartInfo,3, null, false));
          }


        }
      }
    })
  }
  chooseLocale=(value)=>{
    const {locale}=this.state;
    // // const localeValue = value;
    localStorage.setItem("locale",value)
    this.setState({
      locale: value,
      onImg:false
    });
    console.log(value);
  }
  onRefresh=()=>{
    this.state.pages.pageNum = 1;
    this.setState({ refreshing: true, isLoading: true ,pages:this.state.pages,newsList:[]});
    setTimeout(() => {
      this.goodContent(this.state.pages);
    }, 600);
    // this.bannerList();

  }
  handleImageLoaded=()=>{
    let {IsImage}=this.state;
    this.setState({
      IsImage:true
    })
  }

  render(){
    let {dispatch} = this.props;
    let {carouselItem,dataSource,dataSourceObj,loading,onImg,isOption,IsImage} = this.state;
    const messages = localeData[localStorage.locale]
    console.log(this.state.locale,isOption)
    const row =(rowData, sectionID, rowID)=>{
      console.log(rowData)
      return (
        <div style={{marginRight:'3%'}}>
            <div  key={rowID} style={{background:'#fff',fontWeight:'bold',padding:'5% 5% 5%',borderRadius:'10px'}} class="item">
              <div onClick={(e)=>{this.handleDetail(e,rowData)}}>
                {IsImage?
                  <img src={handleOSS(rowData.img_url)} style={{width:'100%',height:'100%'}}   onLoad={this.handleImageLoaded}/>
                  :<img src="image/falls.png" style={{width:'100%',height:'100%'}}   onLoad={this.handleImageLoaded}/>}
              </div>
              <div style={{overflow:'hidden',margin:'10% 0px 0px'}}>
                <p className="ellipsis2" style={{margin:'12px 0px 0px',textAlign:'left',color:'#595867',fontSize:'13px',}}>{rowData.goods_name}</p>
                <div style={{overflow:'hidden',marginTop:'8px'}}>
                  <div style={{float:'left',color:'#F09600',fontSize:'15px',marginTop:'5px'}}>€{rowData.price}</div>
                  <div style={{float:'right',width:'34px',height:'34px'}} onClick={(e) => {this.handleAdd(e,rowData) }}>
                    <img src="image/cart1.png" style={{width:'32px',height:'32px'}}/>
                  </div>
                </div>

              </div>

              {/*<Button type="primary" size="small" inline style={{marginBottom:'1em'}} onClick={(e) => {this.handleAdd(e,i) }}>+ADD</Button>*/}
            </div>


        </div>

      )
    }
    if (loading) {
      return (
        <div className="normal">
          <ActivityIndicator toast text="正在加载" animating={true} />
        </div>
      )
    }
    return(
      <div style={{background:'rgb(249, 247, 247)'}}>
        <IntlProvider
          locale={ this.state.locale } messages={messages}
        >
          <div>
            {isOption?
              <div >
                {/*{onImg?<img src="image/china.png" style={{position:'fixed',top:'3%',left:'2%',zIndex:'100',width:'16px',height:'16px'}}/>:''}*/}
                <Select
                defaultValue="zh"
                onChange={this.chooseLocale}
                bordered={false}
                style={{position:'fixed',top:'3%',left:'4%',zIndex:'200',width:'20%',}}
              >
                {/*<Option key="cn" value="en">English</Option>*/}
                <Option  key="it" value="it">
                  <div className="demo-option-label-item" style={{fontSize:'12px'}}>
                  <span role="img" aria-label="IT">
                    <img src="image/Italy.png" style={{width:'16px',height:'16px',marginRight:'3px'}}/>
                  </span>
                    IT
                  </div>
                </Option>
                <Option  key="en" value="zh" >
                  <div className="demo-option-label-item" style={{fontSize:'12px'}}>
                  <span role="img" aria-label="ZH">
                    <img src="image/china.png" style={{width:'16px',height:'16px',marginRight:'3px'}}/>
                  </span>
                    CN
                  </div>
                </Option>

              </Select>
              </div>:
              <div>
                {/*{onImg?<img src="image/Italy.png" style={{position:'fixed',top:'3%',left:'2%',zIndex:'100',width:'16px',height:'16px'}}/>:""}*/}
                <Select
                  defaultValue="it"
                  onChange={this.chooseLocale}
                  bordered={false}
                  style={{position:'fixed',top:'3%',left:'4%',zIndex:'200',width:'20%',}}
                >
                  {/*<Option key="cn" value="en">English</Option>*/}
                  <Option  key="it" value="it">
                    <div className="demo-option-label-item" style={{fontSize:'12px'}}>
                  <span role="img" aria-label="IT">
                    <img src="image/Italy.png" style={{width:'16px',height:'16px',marginRight:'3px'}}/>
                  </span>
                      IT
                    </div>
                  </Option>
                  <Option  key="en" value="zh" >
                    <div className="demo-option-label-item" style={{fontSize:'12px'}}>
                  <span role="img" aria-label="ZH">
                    <img src="image/china.png" style={{width:'16px',height:'16px',marginRight:'3px'}}/>
                  </span>
                      CN
                    </div>
                  </Option>

                </Select>
              </div>
            }


          <div maxLength={8} style={{position:'fixed',top:'2%',left:'3%',width:'92%',zIndex:'100',height:'44px',border:'1px solid #ddd',borderRadius:'15px',background:"#fff"}} onClick={()=>{goToPage({ dispatch, config: { url: "/searchPage" }, isReplace: false })}}>
            <div style={{position:'absolute',top:'25%',left:'37%'}}>
              <img src="image/search_24px.png" style={{width:'24px',height:'24px'}}/><span style={{color:'#C9C9C9',fontSize:'13px'}}>{messages.searchPlaceholder}</span>
            </div>
          </div>
          </div>
          <Carousel
            autoplay={true}
            infinite
            autoplayInterval={10000}
            speed={400}
          >
            {this.state.carouselItem.map((i,k) => (
              <a
                key={k}
                style={{ display: 'inline-block', width: '100%', height: this.state.imgHeight }}
              >
                <img
                  src={handleOSS(i.url)}
                  alt=""
                  style={{ width: '100%', verticalAlign: 'top',height:'237px' }}
                  onLoad={() => {
                    // fire window resize event to change height
                    this.setState({ imgHeight: '237px' });
                  }}
                />
              </a>
            ))}
          </Carousel>
          <p style={{color:'#2E2D35',fontSize:'17px',margin:'16px 16px 0px'}}>Più venduti</p>
            <ListView
              ref={el => this.lv = el}
              dataSource={this.state.dataSource}
              renderRow={row}
              useBodyScroll
              onEndReachedThreshold={10}
              onEndReached={this.onEndReached}
              pageSize={5}
              scrollEventThrottle={1}
              renderFooter={() => (<div style={{ padding:'0px 0px 40px' , textAlign: 'center' }}>
                {this.state.isLoading ? 'Loading...' : 'Loaded'}
              </div>)}
               pullToRefresh={<PullToRefresh
                 refreshing={this.state.refreshing}
                 onRefresh={this.onRefresh}
               />}
            >

            </ListView>
          {/*{this.goodList()}*/}
          {/*<ul className="macy-container">*/}
            {/*<li>*/}
              {/*<img src="https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1078861629,3747050294&fm=26&gp=0.jpg"/>*/}
              {/*<p>瀑布流</p>*/}
            {/*</li>*/}
            {/*<li>*/}
              {/*<img src="https://dss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1089874897,1268118658&fm=26&gp=0.jpg"/>*/}
              {/*<p>瀑布流</p>*/}
            {/*</li>*/}
            {/*<li>*/}
              {/*<img src="https://dss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1089874897,1268118658&fm=26&gp=0.jpg"/>*/}
              {/*<p>瀑布流</p>*/}
            {/*</li>*/}
            {/*<li>*/}
              {/*<img src="https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1091405991,859863778&fm=26&gp=0.jpg"/>*/}
              {/*<p>瀑布流</p>*/}
            {/*</li>*/}
            {/*<li>*/}
              {/*<img src="https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1078861629,3747050294&fm=26&gp=0.jpg"/>*/}
              {/*<p>瀑布流</p>*/}
            {/*</li>*/}
            {/*<li>*/}
              {/*<img src="https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1078861629,3747050294&fm=26&gp=0.jpg"/>*/}
              {/*<p>瀑布流</p>*/}
            {/*</li>*/}
          {/*</ul>*/}
          <div style={{position:'fixed',bottom:'0px',left:'0px',width:'100%'}}>
            <TabBar
              unselectedTintColor="#949494"
              tintColor="#F09600"
              barTintColor="white"
              hidden={this.state.hidden}
            >
              <TabBar.Item
                title={messages.home}
                key="Life"
                icon={<div style={{
                  width: '24px',
                  height: '24px',
                  background: 'url(image/home2.png) center center /  21px 21px no-repeat' }}
                />
                }
                selectedIcon={<div style={{
                  width: '24px',
                  height: '24px',
                  background: 'url(image/home3.png) center center /  21px 21px no-repeat' }}
                />
                }
                selected={this.state.selectedTab === 'redTab'}
                onPress={() => {
                  this.setState({
                    selectedTab: 'redTab',
                  });
                  goToPage({ dispatch, config: { url: "/shop_home" }, isReplace: false })
                }}
                data-seed="logId"
              >

              </TabBar.Item>
              <TabBar.Item
                icon={
                  <div style={{
                    width: '24px',
                    height: '24px',
                    background: 'url(image/category.png) center center /  21px 21px no-repeat' }}
                  />
                }
                selectedIcon={
                  <div style={{
                    width: '24px',
                    height: '24px',
                    background: 'url(image/category1.png) center center /  21px 21px no-repeat' }}
                  />
                }
                title={messages.category}
                key="Koubei"

                selected={this.state.selectedTab === 'blueTab'}
                onPress={() => {
                  this.setState({
                    selectedTab: 'blueTab',
                  });
                  goToPage({ dispatch, config: { url: "/category" }, isReplace: false })
                }}
                data-seed="logId1"
              >

              </TabBar.Item>
              <TabBar.Item
                icon={
                  <div style={{
                    width: '24px',
                    height: '24px',
                    background: 'url(image/cart4.png) center center /  21px 21px no-repeat' }}
                  />
                }
                selectedIcon={
                  <div style={{
                    width: '24px',
                    height: '24px',
                    background: 'url(image/cart5.png) center center /  21px 21px no-repeat' }}
                  />
                }
                title={messages.cart}
                key="Friend"
                selected={this.state.selectedTab === 'greenTab'}
                onPress={() => {
                  this.setState({
                    selectedTab: 'greenTab',
                  });
                  goToPage({ dispatch, config: { url: "/goodcart" }, isReplace: false })
                }}
              >
              </TabBar.Item>
              <TabBar.Item
                icon={{ uri: 'image/my.png' }}
                selectedIcon={{ uri: 'image/my1.png' }}
                title={messages.my}
                key="my"
                selected={this.state.selectedTab === 'yellowTab'}
                onPress={() => {
                  this.setState({
                    selectedTab: 'yellowTab',
                  });
                  goToPage({ dispatch, config: { url: "/my" }, isReplace: false })
                }}
              >
              </TabBar.Item>
            </TabBar></div>
        </IntlProvider>


      </div>
    )
  }
}
